<script setup lang="ts">
import type { PaginationProps, TableColumns } from "@pureadmin/table";
import { PlusColumn, PlusDialogForm, PlusPage } from "plus-pro-components";
import { computed, onMounted, watch } from "vue";
import { ref, reactive } from "vue";
import { Column, FormPermission, ModelFormOpts, PageOptions } from "./type";
import SearchField from "./SearchField.vue";
import TableEditForm from "./TableEditForm.vue";
import ModelFormView from "./widgets/ModelFormView.vue";

defineOptions({
  name: "CrudPage"
});

// 组件属性
const props = withDefaults(defineProps<PageOptions>(), {
  title: "",
  defaultExpandAll: false,
  bordered: false,
  headerCellStyle: {
    background: "var(--el-fill-color-light)",
    color: "var(--el-text-color-primary)"
  }
});

// 组件emit事件
const emit = defineEmits([
  "update:modelValue",
  "editConfirm",
  "createConfirm",
  "deleteConfirm"
]);

const formEditRef = ref();

const editOptions = ref<ModelFormOpts | null>(null);
const createOptions = ref<ModelFormOpts | null>(null);

const refreshList = (params: any) => {
  reloadData(params);
};

// 页面内实例数据
const listData = ref<any[]>(props.modelValue || []);

// 查询参数
const queryParam = ref<any>({});

// loading
const loading = ref<boolean>(false);

// 分页配置
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 15, 20],
  total: 0,
  align: "right",
  background: true,
  size: "default"
});

const getDataList = async (params: any) => {
  if (!props.getDataList) return;
  loading.value = true;
  props
    .getDataList(params)
    .then(({ total, list }) => {
      listData.value = list || [];
      pagination.total = total || 0;
    })
    .catch(e => {
      console.log("get data list error", e);
    })
    .finally(() => {
      loading.value = false;
    });
};

const reloadData = async (params?: any) => {
  return getDataList({
    ...queryParam.value,
    ...(params || {}),
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize
  });
};

// form domain
const shouldEditRow = (row: any) => {
  console.log("should edit row", row);
  formEditRef.value.open(row, "edit", editOptions.value);
};

const shouldCreate = () => {
  formEditRef.value.open({}, "create", createOptions.value);
};

const onConfirm = (data: any, symbol: string) => {
  switch (symbol) {
    case "create":
      createConfirm(data);
      break;
    case "edit":
      editConfirm(data);
      break;
  }

  reloadData();
};

//
const editConfirm = (row: any) => {
  emit("editConfirm", row);
};

const createConfirm = (row: any) => {
  emit("createConfirm", row);
};

const onPageSizeChanged = (ps: number) => {
  pagination.pageSize = ps;
  reloadData();
};
const onPageNumChanged = (pn: number) => {
  pagination.currentPage = pn;
  reloadData();
};

const mergeEditOption = (): ModelFormOpts => {
  return {
    columns: props.columns
      ?.filter(col => (col.edit ? (col.editable = true) : col.edit))
      .sort((a, b) => (a.editSort || 0) - (b.editSort || 0)),
    title: "编辑" + props.title,
    viewType: "dialog",
    ...props.edit
  };
};

const mergeCreateOption = (): ModelFormOpts => {
  return {
    columns: props.columns
      ?.filter(col => (col.create ? (col.editable = true) : col.create))
      .sort((a, b) => (a.createSort || 0) - (b.createSort || 0)),
    title: "新增" + props.title,
    viewType: "dialog",
    ...props.create
  };
};

watch(
  () => props.modelValue,
  val => {
    listData.value = val;
  }
);
onMounted(() => {
  reloadData();

  editOptions.value = mergeEditOption();
  createOptions.value = mergeCreateOption();
});

defineExpose({
  formData: () => formEditRef.value.data()
});
</script>

<template>
  <div class="plus-table">
    <ModelFormView ref="formEditRef" @on-submit="onConfirm">
      <template v-for="slot in Object.keys($slots)" #[slot]="scope">
        <slot :name="slot" v-bind="scope" :edit="shouldEditRow" />
      </template>
    </ModelFormView>

    <div class="toolbar">
      <slot name="toolbar-title" :create="shouldCreate">
        <el-space>
          <el-button type="primary" @click="shouldCreate">新增</el-button>
          <el-button type="primary">删除</el-button>
        </el-space>
      </slot>
      <slot name="toolbar-action" :search="refreshList">
        <el-space>
          <el-button type="primary" icon="Refresh" text />
        </el-space>
      </slot>
    </div>

    <!-- table -->
    <pure-table
      adaptive
      :data="listData"
      :columns="props.columns"
      :row-key="props.rowKey"
      :border="props.bordered"
      :pagination="pagination"
      :default-expand-all="props.defaultExpandAll"
      :header-cell-style="props.headerCellStyle"
    >
      <template v-for="slot in Object.keys($slots)" #[slot]="scope">
        <slot :name="slot" v-bind="scope" :edit="shouldEditRow" />
      </template>
    </pure-table>
  </div>
</template>

<style lang="scss" scoped>
.plus-table {
  display: flex;
  flex: 1;
  width: 100%;
  // height: 100%;
  flex-direction: column;
  padding: 0.5rem 1rem;
  background-color: var(--el-color-white);
}
.search {
  padding: 0.5rem 0;
}

.toolbar {
  display: flex;
  padding: 0.5rem 0;
  justify-content: space-between;
}
</style>
